package com.bugstack.domain.award.rule.impl;

import com.bugstack.domain.award.model.aggregate.GiveOutPrizesAggregate;
import com.bugstack.domain.award.model.entity.DistributeAwardEntity;
import com.bugstack.domain.award.model.entity.UserAwardRecordEntity;
import com.bugstack.domain.award.model.entity.UserCreditAwardEntity;
import com.bugstack.domain.award.model.valobj.AwardStateVO;
import com.bugstack.domain.award.repository.IAwardRepository;
import com.bugstack.domain.award.rule.IDistributeAward;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.MathContext;

/**
 * @Author: czb
 * @Description: TODO
 * @DateTime: 2025/4/14 12:52
 **/
@Slf4j
@Component("user_credit_random")
public class UserCreditRandomAward implements IDistributeAward{

    @Resource
    private IAwardRepository awardRepository;

    @Override
    public void giveOutPrizes(DistributeAwardEntity distributeAwardEntity) {
        Integer awardId = distributeAwardEntity.getAwardId();
        String awardConfig = distributeAwardEntity.getAwardConfig();
        if (null == awardConfig){
            awardConfig = awardRepository.queryAwardConfigByAwardId(awardId);
        }
        String[] creditRange = awardConfig.split(",");
        if (creditRange.length != 2){
            throw new RuntimeException("award_config 「" + awardConfig + "」配置不是一个范围值，如 1,100");
        }
        BigDecimal creditAmount = generateRandomCredit(new BigDecimal(creditRange[0]), new BigDecimal(creditRange[1]));
        // 构建聚合对象
        UserAwardRecordEntity userAwardRecordEntity = GiveOutPrizesAggregate.buildDistributeUserAwardRecordEntity(
                distributeAwardEntity.getUserId(),
                distributeAwardEntity.getOrderId(),
                distributeAwardEntity.getAwardId(),
                AwardStateVO.complete
        );

        UserCreditAwardEntity userCreditAwardEntity = GiveOutPrizesAggregate.buildUserCreditAwardEntity(distributeAwardEntity.getUserId(), creditAmount);

        GiveOutPrizesAggregate giveOutPrizesAggregate = new GiveOutPrizesAggregate();
        giveOutPrizesAggregate.setUserId(distributeAwardEntity.getUserId());
        giveOutPrizesAggregate.setUserAwardRecordEntity(userAwardRecordEntity);
        giveOutPrizesAggregate.setUserCreditAwardEntity(userCreditAwardEntity);

        // 存储发奖对象
        awardRepository.saveGiveOutPrizesAggregate(giveOutPrizesAggregate);
    }

    private BigDecimal generateRandomCredit(BigDecimal min, BigDecimal max) {
        BigDecimal randomBigDecimal = min.add(BigDecimal.valueOf(Math.random()).multiply(max.subtract(min)));
        return randomBigDecimal.round(new MathContext(3));
    }
}
